<template>
	<view class="page-bg">
		<u-navbar :autoBack="true" :border="false" :placeholder="true">
			<view slot="center" class="fb c3 f16">
				结算订单
			</view>
		</u-navbar>
		<view class="">
			<view class="item-bg mt10">
				<view class="c3 f16 fb ">
					结算品类
				</view>
				<view class="divider-line mt10 mb10" />

				<view class="f" style=" overflow-x: auto;white-space: nowrap;">
					<view class="f-f-c-c f14" style="width: 80px;"
						:class="[current==index?'select-item cm':'unselect-item c3']" v-for="item,index in options"
						:style="{marginLeft:index!=0?'20px':'0px'}" :key="index" @click="changeType(index)">
						<image :src="item.imgUrl" style="width: 80px;height: 60px;"></image>
						<view class="f14">
							{{item.name}}
						</view>
					</view>
				</view>
				<view
					style="display: grid;  grid-template-columns: 49% 49%;column-gap: 2%; row-gap: 10px; margin-top: 10px;"
					v-if="current==index" v-for="item,index in options" :key="index">
					<view class="f-s-b f14" :class="[currentItem==indexChild?'recycle-bg':'unrecycle-bg']"
						v-for="data,indexChild in item.childCategorizeVoList" :key="indexChild"
						@click="changeRecycle(indexChild)">
						<view class="ml10">
							{{data.name}}
						</view>
						<view class="mr10" v-if="data.priceType=='1'">
							可议价
						</view>
						<view class="mr10" v-else>
							{{data.price}}/{{data.unit}}
						</view>
					</view>
				</view>
				<view class="divider-line mt10 mb10"></view>
				<view class="sure-btn" style="width: 150px; margin: 0 auto;" @click="showAddDialog"> 添加</view>


			</view>

			<view class="item-bg mt10">
				<view class="c3 f16 fb ">
					已称重品类
				</view>
				<view class="divider-line mt10 mb10" />
				<view class="add-order" v-for="item,index in addItem" :key="index">
					<view>
						{{item.categorizeName}}
					</view>
					<view>
						{{Number(item.weight).toFixed(2)}}{{item.unit}}
					</view>
					<view>
						￥{{item.totalPrice.toFixed(2)}}
					</view>
					<u-icon name="close-circle-fill" color="red" size="24" @click="deleteAdd(index)"></u-icon>

				</view>

			</view>


			<view class="item-bg p12 mt10">
				<view class="c3 fb f16 ">
					预约订单信息
				</view>
				<view class="divider-line mb10 mt10" />
				<view class="f-s-b">
					<view class="c6 f14 mt10">
						订单编号：
					</view>
					<view class="fb f14 c3">
						{{orderInfo.orderNo}}
					</view>
				</view>
				<view class="f-s-b mt10">
					<view class="c6 f14 mt10">
						创建时间：
					</view>
					<view class="fb f14 c3">
						{{orderInfo.createTime}}
					</view>
				</view>
				<view class="f-s-b mt10">
					<view class="c6 f14 mt10">
						接单时间：
					</view>
					<view class="fb f14 c3">
						{{orderInfo.takingTime}}
					</view>
				</view>
			</view>

			<view class="item-bg p12 mt10">
				<view class="c3 fb f16 ">
					回收信息
				</view>
				<view v-for="item,index in orderInfo.hsUserWasteVoList" :key="index">
					<view class="divider-line mb10 mt10" />
					<view class="f-s-b">
						<view class="c6 f14 mt10">
							物品类型：
						</view>
						<view class="fb f14 c3">
							{{item.categorizeName}}
						</view>
					</view>
					<view class="f-s-b">
						<view class="c6 f14 mt10">
							计量类型：
						</view>
						<view class="fb f14 c3">
							{{countTypes[item.countType]}}
						</view>
					</view>
					<view class="f-s-b">
						<view class="c6 f14 mt10">
							计量单位：
						</view>
						<view class="fb f14 c3">
							{{item.unit}}
						</view>
					</view>
					<view class="f-s-b">
						<view class="c6 f14 mt10">
							{{item.countType==0?'预估重量':'数量'}}：
						</view>
						<view class="fb f14 c3">
							{{Number(item.weight).toFixed(2)}} {{item.unit}}
						</view>
					</view>
					<view class="f-s-b mt10">
						<view class="c6 f14 mt10">
							预估金额：
						</view>
						<view class="fb f14 c3">
							¥{{item.amount}}
						</view>
					</view>
					<view class="f-s-b mt10">
						<view class="c6 f14 mt10">
							物品图片：
						</view>
						<u--image :src="item.imgUrl" width="80px" height="80px"></u--image>
					</view>
				</view>
			</view>

			<view class="item-bg p12 mt10">
				<view class="c3 fb f16 ">
					结算方式
				</view>
				<view class="divider-line mb10 mt10" />
				<u-radio-group v-model="payType" placement="row">
					<u-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in radiolist1" :key="index"
						:label="item.label" :name="item.name">
					</u-radio>
				</u-radio-group>
			</view>

			<view class="f ml20 mr20 pb30" style="margin-top: 40px;">
				<view class="sure-circle-btn f1" style="height: 44px;" @click="confirm">
					提交结算
				</view>
			</view>

		</view>
		<u-popup :round="10" :show="showAdd" mode="center" @close="closePop" :closeable="true">
			<view class="c3" style="width: 100vw;">
				<view class="f-f-c-c fb f18 mt10 mb10">
					添加
				</view>
				<view class="f ml10">
					<view>种类</view>
					<view class="input-bg f-s-b f1 m15">
						<uni-data-select v-model="currentItem" :localdata="list" :clear="false"></uni-data-select>
					</view>
				</view>
				<view class="f ml10">
					<view>单价</view>
					<view class="input-bg f-s-b f1 m15 pl10 pr10">
						<u-input :placeholder="placeValue" v-model="price" border="none" @change="changePrice"
							:disabled="currentRecyc.priceType!='1'" />
							<view> 元</view>
					</view>
				</view>
				<view class="f ml10">
					<view v-show="currentRecyc.countType==0">重量</view>
					<view v-show="currentRecyc.countType==1">数量</view>
					<view class="input-bg f-s-b f1 m15 pl10 pr10">
						<u-input v-model="weight" @change="changeWeight" border="none"
							:disabled="disableIn=='0'"></u-input>
						<view>{{currentRecyc.unit}}</view>
					</view>
				</view>
				<view class="f ml10">
					<view>图片</view>
					<view class="f-s-b f1 m15 pl10 pr10">
						<view style="width: 70px;height: 70px;" @click="changeAvatar">
							<image v-if="recyclerImgUrl" :src="recyclerImgUrl" style="width: 70px;height: 70px;">
							</image>
							<u-icon v-else name="photo" size="70"></u-icon>
						</view>
					</view>
				</view>
				<view class="f ml10">
					<view>方式</view>
					<view class=" f-s-b f1 m15 pl10 pr10">
						<u-radio-group v-model="disableIn" placement="row">
							<u-radio label="自动输入" name="0">
							</u-radio>
							<u-radio :customStyle="{marginLeft: '8px'}" label="手动输入" name="1">
							</u-radio>
						</u-radio-group>
					</view>
				</view>


				<view class="sure-input f-f-c-c" @click="addRecycler">
					确认
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
     import * as config from '@/config'
	export default {

		data() {
			return {
				id: '',
				isConnectBlueTooth: false,
				showAdd: false,
				disableIn: '0',
				current: 0,
				currentItem: 0,
				price: 0,
				weight: 0,
				totalPrice: 0,
				orderInfo: {
					orderNo:'',
					createTime:'',
					takingTime:'',
					expectWeightTal:0,
					expectAmountTal:0,
					startTime:'',
					endTime:'',
					arriveTime:'',
					completeTime:'',
					contactor:'',
					phone:'',
					province:'',
					city:'',
					address:'',
					county:'',
					status:0,
				},
				list: [],
				options: [],
				addItem: [],
				appointOrderId: '',
				recyclerImgUrl: undefined,
				radiolist1: [],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				payType: '0',
				currentRecyc: {},
				placeValue: '',
				countTypes:['重量','数量'],

			}
		},
		onLoad(Option) {
			this.getPayType()
			this.getInfo()
			if (Option.id) {
				this.appointOrderId = Option.id
				this.id = this.appointOrderId
				this.getOrderInfo()
			}
			if (Option.orderId) {
				this.appointOrderId = Option.orderId
				this.id = Option.orderId
				this.getOrderInfo()
			}
			let that = this




			// uni.getConnectedBluetoothDevices({
			// 	fail(err) {
			// 		uni.getStorage({
			// 			key: 'blueTooth',
			// 			success(res) {
			// 				let data = JSON.parse(res.data)
			// 				that.initBlue(data)
			// 			},
			// 			fail(refs) {
			// 				uni.hideLoading()
			// 				// uni.showToast({
			// 				// 	title: '连接失败错误码:' + refs.errCode,
			// 				// })
			// 			}
			// 		});
			// 	},
			// 	success(res) {
			// 		if (res.devices.length > 0) {
			// 			that.isConnectBlueTooth = true
			// 			let data = {
			// 				data: res.devices[0].name,
			// 				deviceId: res.devices[0].deviceId
			// 			}
			// 			that.initService(data)
			// 		}
			// 	}
			// })
		},

		methods: {
			showAddDialog(){
				this.showAdd=true;
				console.log(this.list)
			},
			closePop() {
				this.showAdd = false
				this.recyclerImgUrl = ''
			},
			getPayType() {
				let that = this
				that.request("get", "system/dict/data/type/pay_type", uni.getStorageSync('token'), null).then(
					res => {
						console.log(res)
						if (res.code === 200) {
							if (res.data.length > 0) {
								that.payType = res.data[0].dictValue
							}
							res.data.forEach(item => {
								that.radiolist1.push({
									name: item.dictValue + '',
									label: item.dictLabel
								})
							})
						}
					})
			},
			changeAvatar() {
				let that = this
				uni.chooseImage({

					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url:  config.def().baseUrl+'/oss/app/upload', //开发者服务器 url
							filePath: tempFilePaths[0],
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('token')
							},
							success: (uploadFileRes) => {
								let data = JSON.parse(uploadFileRes.data)
								if (data.code == 200) {
									that.recyclerImgUrl = data.data.url
								}
							},
							fail: (res) => {
								console.log(res)
							}
						});
					}
				});

			},
			// initService(data) {
			// 	console.log(data, 'service ')
			// 	let that = this
			// 	setTimeout(function() {
			// 		// 连接成功后，获取该设备服务列表
			// 		uni.getBLEDeviceServices({
			// 			deviceId: data.deviceId,
			// 			success(res) {
			// 				res.services.forEach((item) => {
			// 					if (res.services.length > 0) {
			// 						that.domain.serviceId = res.services[3]
			// 							.uuid //根据我们的设备  使用的是第三个服务
			// 						// // 通过服务，发现特征值
			// 						setTimeout(function() {
			// 							uni.getBLEDeviceCharacteristics({
			// 								deviceId: that.domain
			// 									.deviceId,
			// 								serviceId: that.domain
			// 									.serviceId,
			// 								success(res) {
			// 									var flag = true;
			// 									var list = res
			// 										.characteristics;
			// 									res.characteristics
			// 										.forEach(
			// 											item => {
			// 												if (
			// 													item
			// 													.properties
			// 													.write &&
			// 													flag
			// 												) {
			// 													that.domain
			// 														.characteristicId =
			// 														item
			// 														.uuid;
			// 													flag =
			// 														false;
			// 												}
			// 												if (item
			// 													.properties
			// 													.notify
			// 												) {
			// 													that.domain
			// 														.characteristicWatchId =
			// 														item
			// 														.uuid;
			// 												}
			// 											})

			// 									setTimeout(
			// 										function() {
			// 											uni.hideLoading()
			// 											uni.showToast({
			// 												title: '连接成功',
			// 											})
			// 										}, 500)
			// 									let dev = {
			// 										data: data.name,
			// 										deviceId: data.deviceId,
			// 										serviceId: that.domain
			// 											.serviceId,
			// 										characteristicId: that
			// 											.domain
			// 											.characteristicWatchId,
			// 									}
			// 									that
			// 										.belNotifyBLECharacteristicValueChange(
			// 											dev);
			// 								},
			// 								fail: (res) => {
			// 									uni.hideLoading()
			// 									console.log(
			// 										res);
			// 								}
			// 							})
			// 						}, 300) // 此步骤很重要，通过每个延迟发送请求来避免同时发送请求出现的bug
			// 					}
			// 				})
			// 			}
			// 		})
			// 	}, 1000)
			// },
			// initBlue(data) {
			// 	let that = this
			// 	uni.openBluetoothAdapter({
			// 		// mode: 'cnetral',// 模式为 cnetral ，此处可不填写
			// 		success(res) {
			// 			console.log(res, '   res')
			// 			that.createBLEConnection(data)
			// 		},
			// 		fail(res) {
			// 			if (res.errMsg == 'openBluetoothAdapter:fail already opened') {
			// 				that.createBLEConnection(data)
			// 			} else {
			// 				// 错误情况，弹出提示
			// 				uni.showToast({
			// 					icon: 'none',
			// 					title: res.errMsg
			// 				})
			// 			}
			// 		},
			// 		complete(res) {}
			// 	})
			// },
			// createBLEConnection(data) {
			// 	console.log(data)
			// 	let name = data.equipmentName
			// 	let devId = data.deviceId
			// 	let that = this
			// 	uni.showLoading({
			// 		title: '正在连接蓝牙...',
			// 		mask: true
			// 	})
			// 	uni.createBLEConnection({
			// 		deviceId: devId,
			// 		success(res) {
			// 			console.log(res)
			// 			that.domain.deviceId = devId;
			// 			// that.domain.serviceId = serviceId;
			// 			that.domain.equipmentName = name;
			// 			uni.hideLoading()
			// 			uni.showToast({
			// 				title: '连接成功',
			// 			})
			// 			setTimeout(function() {
			// 				that.belNotifyBLECharacteristicValueChange(data)
			// 			}, 2000)
			// 		},
			// 		fail(ress) {
			// 			uni.hideLoading()
			// 			if (ress.errMsg == 'createBLEConnection:fail already connect') {
			// 				setTimeout(function() {
			// 					that.belNotifyBLECharacteristicValueChange(data)
			// 				}, 2000)
			// 				uni.showToast({
			// 					title: '连接成功',
			// 				})
			// 				return
			// 			}
			// 			uni.showToast({
			// 				title: '连接失败错误码:' + ress.errCode + ' 请检查蓝牙状态',
			// 			})
			// 		}
			// 	})
			// },
			// belNotifyBLECharacteristicValueChange(data) {
			// 	let that = this
			// 	console.log(data)
			// 	uni.notifyBLECharacteristicValueChange({
			// 		deviceId: data.deviceId,
			// 		serviceId: data.serviceId,
			// 		characteristicId: data.characteristicId,
			// 		state: true,
			// 		success(res) {
			// 			console.log(res, '   reaaa')
			// 			uni.onBLECharacteristicValueChange(function(res1) {
			// 				let readText = that.publicTools.ab2hex(res1.value)
			// 				that.datastr = readText;
			// 				if (that.disableIn == '0') {
			// 					that.weight = that.datastr
			// 				}
			// 			})
			// 		},
			// 		fail: (res) => {
			// 			console.log(res, '   222')
			// 			uni.showToast({
			// 				icon: 'none',
			// 				title: '设备暂不支持接收数据',
			// 				duration: 3000
			// 			})
			// 		}
			// 	})
			// },
			getOrderInfo() {
				let that = this
				that.request("get", "riderAppOrder/app/" + that.id, uni.getStorageSync('token'), null).then(
					res => {
						console.log(res)
						if (res.code === 200) {
							that.orderInfo = res.data
							// that.hsUserWasteVoList = res.data.hsUserWasteVoList
						}
					})
			},
			getInfo() {
				let that = this
				that.request("get", "categorize/app/allList", null, null).then(res => {
					if (res.code == 200) {
						that.options = res.data
						that.list = []
						that.price = that.options[that.current].childCategorizeVoList[that.currentItem].price
						that.currentRecyc = that.options[that.current].childCategorizeVoList[0]
						let item = that.options[that.current].childCategorizeVoList;
						item.forEach(function(each) {
							that.list.push({
								text: each.name,
								value: item.indexOf(each)
							})
						})
					}
				})
			},
			navToView(url) {
				uni.navigateTo({
					url: url
				})
			},
			closeItem() {
				this.changeRecycle(this.currentItem)
			},
			close() {
				this.showAdd = false
			},
			changeType(value) {
				this.current = value
				this.changeRecycle(0)
			},
			changeRecycle(value) {
				this.currentItem = value
				this.list = []
				let item = this.options[this.current].childCategorizeVoList;
				let taht = this
				item.forEach(function(each) {
					taht.list.push({
						text: each.name,
						value: item.indexOf(each)
					})
				})
				this.currentRecyc = this.options[this.current].childCategorizeVoList[value]
				if (this.currentRecyc.priceType == '1') {
					this.placeValue = "可议价"
					this.price = ""
					this.totalPrice = 0
				} else {
					this.placeValue = ""
					this.price = this.options[this.current].childCategorizeVoList[value].price
					this.totalPrice = this.price * this.weight
				}
			},
			changeWeight(e) {
				this.weight = e
				this.totalPrice = this.price * this.weight
			},
			changePrice(e) {
				this.price = e
				this.totalPrice = this.price * this.weight
			},
			deleteAdd(value) {
				console.log(value, ' delete')
				this.addItem.splice(value, 1)
			},
			addRecycler() {
				this.showAdd = false
				if (this.weight == 0) {
					return
				}
				let name = this.options[this.current].childCategorizeVoList[this.currentItem].name
				let item = this.options[this.current].childCategorizeVoList[this.currentItem]
				let ins=false
				let inItem
				this.addItem.forEach(it=>{
					if(it.categorizeId==item.id){
						ins=true
						inItem=it
					}
				})
				if(ins){
					this.addItem.forEach(it=>{
						if(it.categorizeId==inItem.categorizeId){
							it.price= this.price
							it.imgUrl= this.recyclerImgUrl
							it.weight= Number(it.weight)+ Number(this.weight)
							it.amount=  Number(it.price) * Number(it.weight)
							it.totalPrice=  Number(it.price) * Number(it.weight)
						}
					})
				}else{
					this.addItem.push({
						categorizeId: item.id,
						categorizeName: item.name,
						unit: item.unit,
						price: Number(this.price),
						imgUrl: this.recyclerImgUrl,
						amount: Number(this.price) * Number(this.weight),
						totalPrice: Number(this.price) * Number(this.weight),
						weight: Number(this.weight),
					})
				}
				this.weight = 0
			},
			confirm() {
				let that = this
				let weightTal = 0
				let amountTal = 0
				that.addItem.map((it) => {
					weightTal += Number(it.weight)
					amountTal += Number(it.amount)
				})
				let params = {
					appointOrderId: that.appointOrderId,
					weightTal,
					amountTal,
					hsUserWasteBoList: that.addItem,
					payType: that.payType
				}
				console.log(params, 'params')
				that.request("post", "riderAppOrder/app/addSettleOrder", uni.getStorageSync('token'),
					params).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '提交成功待确认'
						})
						uni.navigateBack({
							delta: 1
						})
					}
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	/deep/ .uni-select {
		border: none;
		width: 80vw;
	}

	.item-bg {
		padding: 12px;
		background: #FFFFFF;
		box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.1);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
	}

	.select-item {
		background: #FFFFFF;
		box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.1);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
		border: 1px solid #1AC388;
	}

	.unselect-item {
		background: #FFFFFF;
		box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.1);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
	}

	.recycle-bg {
		font-size: 14px;
		color: #1AC388;
		height: 34px;
		background: rgba(26, 195, 136, 0.24);
		border-radius: 4px 4px 4px 4px;
		border: 1px solid #1AC388;
	}

	.unrecycle-bg {
		font-size: 14px;
		color: #999999;
		height: 34px;
		background: rgba(255, 255, 255, 0.24);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
		border: 1px solid #CCCCCC;
	}

	.add-order {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 14px;
		color: #333333;
		margin: 10px auto;
		padding: 10px;
		background: rgba(204, 204, 204, 0.24);
		border-radius: 4px 4px 4px 4px;
		opacity: 1;
		border: 1px solid #CCCCCC;
	}

	.input-bg {
		height: 44px;
		background: #FAFAFA;
		border-radius: 4px 4px 4px 4px;
		border: 1px solid #E4E4E4;
	}



	.hand-input {
		width: 80%;
		margin: 10px auto;
		color: #1AC388;
		font-size: 16px;
		height: 44px;
		background: rgba(26, 195, 136, 0.1);
		border-radius: 22px 22px 22px 22px;
		border: 1px solid #1AC388;
	}

	.auto-input {
		width: 80%;
		margin: 10px auto;
		height: 44px;
		color: #1AC388;
		font-size: 16px;
		background: rgba(26, 195, 136, 0.1);
		border-radius: 22px 22px 22px 22px;
		border: 1px solid #1AC388;
	}

	.sure-input {
		width: 80%;
		margin: 10px auto;
		height: 44px;
		color: #FFFFFF;
		font-size: 16px;
		background: #1AC388;
		border-radius: 22px 22px 22px 22px;
		opacity: 1;
	}
</style>
